package com.chunuo.oss.controller;

import com.aliyun.oss.OSS;
import com.chunuo.commonutils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 类的作用
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-07-05 16:03
 */
@RestController
@Slf4j
//@CrossOrigin
public class OSSClientController {

    @Autowired
    OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @RequestMapping("/oss/client/policy")
    public R upload(MultipartFile file) throws IOException {
        // 上传文件流。
        InputStream inputStream = file.getInputStream();

        // new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + uuid + "/" + 文件名;
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        ;
        String fileName = date + "/"+uuid+file.getOriginalFilename();
        log.info("fileName = {}",fileName);

        ossClient.putObject(bucket, fileName, inputStream);

        // 关闭OSSClient。
//        ossClient.shutdown();
        inputStream.close();

        System.out.println("上传完成...");
        // 拼接路径
        return R.ok().data("url","https://"+bucket+"."+ endpoint +"/"+fileName);
    }



}
